"""
__author__ = 'berlinyoung'
@File   :base.py
@Date   :2022/6/12 22:02
-*- coding: utf-8 -*-
"""
import time

from appium.webdriver.common.mobileby import MobileBy
from appium.webdriver.common.touch_action import TouchAction
from appium.webdriver.webdriver import WebDriver
from selenium.common import NoSuchElementException


class Base:

    def __init__(self,driver:WebDriver = None):
        self.driver = driver

    def find(self,by,locator):
        return self.driver.find_element(by,locator)
    def finds(self,by,locator):
        return self.driver.find_elements(by,locator)
    def find_and_click(self,by,locator):
        return self.find(by,locator).click()
    def find_and_keys(self,by,locator,text):
        return self.find(by, locator).send_keys(text)
    def find_get(self,by,locator):
        return self.find(by,locator).get_attribute("text")

    def swipe_find_get(self,by,locator,num=3):
        for i in range(num):
            if i == num - 1:
                raise NoSuchElementException(f"找了{num-1}次，未找到")
            # 方法一，不要让find_element抛异常，在except中捕获异常，实现滑动操作
        try:
            get_info = self.find(by,locator).get_attribute('text')
            return get_info
        except:
            # 滑动
            size = self.driver.get_window_size()
            # 'width','height'
            width = size.get('width')
            height = size.get('height')

            start_x = width/2
            start_y = height*0.2

            end_x = start_x
            end_y = height*0.8
            duration = 2000

            self.driver.swipe(start_x, start_y, end_x, end_y, duration)

    def touch_tap(self,x,y):
        action = TouchAction(self.driver)
        return action.tap(x=x,y=y).perform().release()
    def tap_login(self):
        self.touch_tap(405, 1800)
        self.touch_tap(405, 1650)
        self.touch_tap(135, 2000)
        self.touch_tap(135, 1800)
        self.touch_tap(405, 2000)
        self.touch_tap(675, 1800)
        self.touch_tap(900, 2000)
    def deal_confirm(self):
        # # 有数字格的“卖出”坐标
        # self.touch_tap(944,2120)
        # # 没数字格的“卖出”坐标
        # self.find_and_click(MobileBy.ID,"tv_submit")
        self.touch_tap(650, 2200)
        self.sleep(1)
        self.touch_tap(540, 2190)   # "确认卖出"按钮，坐标(540,2190)
        self.sleep(1)
        self.touch_tap(810, 2200)   # 点击“确认卖出”后，出现“撤单”和“当日委托”，点击“当日委托”进入到委托查看

    def sleep(self,sec):
        return time.sleep(sec)
    def local_time(self):
        return time.localtime()
    def strftime(self,format):
        return time.strftime(format,self.local_time())


